package com.example.accessingdatamysql;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestBody;
import com.alibaba.fastjson.JSON;
import java.util.Map;


@Controller // This means that this class is a Controller
@RequestMapping(path="/api") // This means URL's start with /api (after Application path)
public class MainController {
  @Autowired // This means to get the bean called todoListRepository Which is auto-generated by Spring, we will use it to handle the data
  private TodoListRepository todoListRepository;

  @GetMapping(path="/getTodos")
  public @ResponseBody Iterable<TodoList> getAllTodos() {
    // This returns a JSON or XML with the todos
    return todoListRepository.findAll();
  }

  @PostMapping(path="/addTodo", produces="application/json;charset=UTF-8") // Map ONLY POST Requests
  public @ResponseBody String addNewTodo (@RequestBody String todo) {
    System.out.println(todo);
    Map<String, Object> todoObj = JSON.parseObject(todo, Map.class);
    Map<String, Object> todoMap = JSON.parseObject(todoObj.get("data").toString(), Map.class);
    TodoList newTodo = new TodoList();
    newTodo.setId(todoMap.get("id").toString());
    newTodo.setText(todoMap.get("text").toString());
    newTodo.setFinished(0);
    todoListRepository.save(newTodo);
    return "Saved";
  }

  @PostMapping(path="/finishTodo", produces="application/json;charset=UTF-8")
  public @ResponseBody String fininshTodo (@RequestBody String todo) {
    Map<String, Object> todoObj = JSON.parseObject(todo, Map.class);
    Map<String, Object> todoMap = JSON.parseObject(todoObj.get("data").toString(), Map.class);
    TodoList newTodo = todoListRepository.findById(todoMap.get("id").toString()).get();
    newTodo.setFinished("true".equals(todoMap.get("finished").toString()) ? 1 : 0);
    todoListRepository.save(newTodo);
    return "Saved";
  }

  @PostMapping(path="/delTodo", produces="application/json;charset=UTF-8")
  public @ResponseBody String deleteTodo (@RequestBody String todo) {
    Map<String, Object> todoObj = JSON.parseObject(todo, Map.class);
    Map<String, Object> todoMap = JSON.parseObject(todoObj.get("data").toString(), Map.class);
    todoListRepository.deleteById(todoMap.get("id").toString());
    return todoMap.get("id").toString();
  }
}